#include "Database.h"
#include "ResultSet.h"

#include <string.h>
#include <memory.h>
#include <stdlib.h>


LIBDBC_BEGIN_NAMESPACE

Database::Database()
{
	_connected = false;
	_szLastError = NULL;
}


Database::~Database()
{
	close();
}

bool Database::hasResultSet(IResultSet* prs)
{
	std::vector<IResultSet*>::iterator i, end;
	i = _results.begin();
	end = _results.end();

	while (i != end)
	{
		if (*i == prs)
		{
			return true;
		}
		i++;
	}
	return false;
}

bool Database::freeResultSet(IResultSet* prs)
{
	std::vector<IResultSet*>::iterator i, end;
	i = _results.begin();
	end = _results.end();

	while (i != end)
	{
		if (*i == prs)
		{
			_results.erase(i);
			delete prs;
			return true;
		}
		i++;
	}
	return false;
}

bool Database::removeFromResultSetWithoutDeletion(IResultSet* prs)
{
	std::vector<IResultSet*>::iterator i, end;
	i = _results.begin();
	end = _results.end();

	while (i != end)
	{
		if (*i == prs)
		{
			_results.erase(i);
			return true;
		}
		i++;
	}
	return false;
}

bool Database::_connect(const char* host, const char* database, const char* user, const char* pwd, int port)
{
	return false;
}

bool Database::_connect(const char* host, const char* user, const char* pwd, int port)
{
	return false;
}

bool Database::_close()
{
	size_t s = _results.size();
	for (size_t i = 0; i<s; i++)
	{
		delete _results[i];
	}
	_results.clear();

	return false;
}

IResultSet* Database::_execQuery(const char* query)
{
	return new ResultSet(this, NULL);
}

int Database::_execInsert(const char* query)
{
	return _execNonQuery(query);
}

int Database::_execUpdate(const char* query)
{
	return _execNonQuery(query);
}

int Database::_execDelete(const char* query)
{
	return _execNonQuery(query);
}

int Database::_execDML(const char* query)
{
	return _execNonQuery(query);
}

void Database::_use(const char* database)
{

}

void Database::_beginTransaction()
{
	_execNonQuery("Begin transaction");
}

bool Database::_commit()
{
	_execNonQuery("commit");
	return true;
}

bool Database::_rollback()
{
	_execNonQuery("rollback");
	return true;
}

int Database::_execNonQuery(const char* query)
{
	return 0;
}

IResultSet* Database::_createResultSet(SqlResult* pResult)
{
	IResultSet* pSet = new ResultSet(this, pResult);
	_results.push_back(pSet);
	return pSet;
}

void Database::_setLastError(const char* err)
{
	if (_szLastError)
		delete _szLastError;

#if defined(WIN32)||defined(WIN64)
	_szLastError = _strdup(err);
#else
	if ((_szLastError = new char[strlen(err) + 1]))
		strncpy(_szLastError, err, strlen(err));
#endif
}

LIBDBC_END_NAMESPACE